package com.xiaoma.mvi

import android.os.Bundle
import android.transition.TransitionInflater
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.xiaoma.mvi.business.Dimens
import com.xiaoma.mvi.databinding.FragmentEnumSelectionBinding
import com.xiaoma.mvi.func.BindingFragment
import com.xiaoma.mvi.func.animFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class EnumSelectionFragment : BindingFragment<FragmentEnumSelectionBinding>() {

    private val vm by viewModels<Vm>()

    override fun onResume() {
        super.onResume()
        enterTransition = TransitionInflater.from(requireContext())
            .inflateTransition(R.transition.fragment_exit)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val leftTransitionX = 0F
        val rightTransitionX =
            (Dimens.enumSelectionItemDimen + Dimens.enumSelectionItemDistance).toFloat()

        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                vm.selection.collectLatest { item ->
                    binding.ivLeftBg.isEnabled = false
                    binding.tvLeft.isEnabled = false

                    binding.ivRightBg.isEnabled = false
                    binding.tvRight.isEnabled = false
                    when (item) {
                        Item.Left -> {
                            animFlow(binding.vIndicator.translationX, leftTransitionX)
                                .collect { binding.vIndicator.translationX = it }
                            binding.ivLeftBg.isEnabled = true
                            binding.tvLeft.isEnabled = true
                        }
                        Item.Right -> {
                            animFlow(binding.vIndicator.translationX, rightTransitionX)
                                .collect { binding.vIndicator.translationX = it }
                            binding.ivRightBg.isEnabled = true
                            binding.tvRight.isEnabled = true
                        }
                    }
                }
            }
        }

        binding.btnLeft.setOnClickListener { vm.select(Item.Left) }
        binding.btnRight.setOnClickListener { vm.select(Item.Right) }
    }

    enum class Item {
        Left,
        Right
    }

    class Vm : ViewModel() {
        private val _selection = MutableStateFlow(Item.Left)
        val selection = _selection.asStateFlow()
        fun select(item: Item) = _selection.update { item }
    }

}